import { formatNumber, messages } from "share/common";
import { USER_DETAIL_COLUMNS, COMMON_REPORT_CONFIG, } from "../constant";
import React from "react";
import Charts from "components/template/graphic-report/report-echarts";
import VScrollEchartsV2 from "components/template/graphic-report/vscroll-echarts";
import ReportTable from "components/template/graphic-report/report-table";
import ApproveEfficiencyService from "../report-private-service/approve-efficiency-report.service";
import { toggleShowLabel, commonUtilsFactory } from "../echarts-data-transfer/utils";
import { getLocalStorageWithAutoParse } from "share/common";
import ReportOverviewSimple from "components/template/graphic-report/report-overview-simple";
import { Icon, Popover } from "antd";
import GraphicReportService from "../graphic-report.service";

const reportKeyPrefix = 'hly.reportLabel.30001.';
const tendencyLabelKey = `${reportKeyPrefix}tendencyReport`;
const nodeTimeLabelKey = `${reportKeyPrefix}nodeTimeReport`;
const formAvgTimeLabelKey = `${reportKeyPrefix}formAvgTimeReport`;
const formAvgNodeLabelKey = `${reportKeyPrefix}formAvgNodeReport`;

// 根据后端返回的 reportColumnDTOList，或者 reportColumnCustomizedDTOList ，获取报表的列
function getReportTableColumn(list) {
  let newArr = [];
  let length = list.length;
  // 用于去重，后端有时候出错会返回重复的项，导致前端抛出大量warning
  let existMap = new Map([]);
  for (let i = 0; i < length; i++) {
    let item = list[i];
    const { columnPropName, hide, columnDisplayName } = item;
    if (!hide && !existMap.has(columnPropName)) {
      item.title = <Popover placement="topLeft" content={columnDisplayName}>{columnDisplayName}</Popover>;
      item.dataIndex = columnPropName;
      item.render = (text) => {
        if (item.dataType === 'bigdecimal')
          text = React.Component.prototype.filterMoney(text)
        const content = text !== undefined && text !== null ?
          <Popover
            content={text}
            placement={item.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}>
            {text}
          </Popover> : '-';
        return <span className='need-limit-100'>{content}</span>;
      }
      item.width = 100;
      newArr.push(item);
      existMap.set(item.dataIndex, true);
    }
  }
  existMap.clear();
  existMap = null;

  return newArr
}

/**
 * 审批效率分析图表
 * id 30001
 *
 * config配置注释见 report-private.service
 */

export default (context) => {
  let tendencyShowLabel = getLocalStorageWithAutoParse(tendencyLabelKey);
  if (tendencyShowLabel === undefined) {
    tendencyShowLabel = true;
  }

  let nodeTimeShowLabel = getLocalStorageWithAutoParse(nodeTimeLabelKey);
  if (nodeTimeShowLabel === undefined) {
    nodeTimeShowLabel = true;
  }

  let formAvgTimeShowLabel = getLocalStorageWithAutoParse(formAvgTimeLabelKey);
  if (formAvgTimeShowLabel === undefined) {
    formAvgTimeShowLabel = true;
  }

  let formAvgNodeShowLabel = getLocalStorageWithAutoParse(formAvgNodeLabelKey);
  if (formAvgNodeShowLabel === undefined) {
    formAvgNodeShowLabel = true;
  }

  return {
    reportOverview: {
      title:
        <span>
          {messages('finance-7.key171')/*报表概览*/}&nbsp;
          <Popover
            content={(
              <div>
                <div>{messages('finance-7.key172')/*节点平均时长=总时长/总节点数*/}</div>
                <div>{messages('finance-7.key173')/*表单平均时长=总时长/总单据数*/}</div>
                <div>{messages('finance-7.key174')/*表单平均节点数=总节点数/总单据数*/}</div>
                <div>{messages('finance-7.key175')/*-其中总节点数为审批历史里的实际经过节点*/}</div>
              </div>
            )}
            placement="rightTop"
          >
          <Icon type="info-circle-o" />
        </Popover>
        </span>,
      isLoading: false,
      fetchMethod: ApproveEfficiencyService.getReportOverview,
      options: [{
        title: messages('finance-7.key176')/*总操作数*/,
        detail: 0
      }, {
        title: messages('finance-7.key177')/*节点平均时长*/,
        detail: 0
      }, {
        title: messages('finance-7.key178')/*表单平均时长*/,
        detail: 0
      }, {
        title: messages('finance-7.key179')/*表单平均节点数*/,
        detail: 0
      }],
      render: ({ config }) => {
        return (
          <ReportOverviewSimple
            title={config.title}
            cols={8}
            data={config.options}
            dataLength={1}
            loading={false}
          />
        )
      }
    },
    formNameTotalReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key180')/*表单*/,
      fetchMethod: ApproveEfficiencyService.getReportFormNameTotal,
      render: ({ config, context }) => {
        let { isFetchingData } = context.state;
        const { isLoading, options, dataLength, title } = config;
        return (
          <Charts
            title={title}
            cols={16}
            dataLength={dataLength}
            options={options}
            reportKey='formNameTotalReport'
            reportType='pie'
            isFetchingData={isFetchingData}
            loading={isLoading}
          />
        )
      }
    },
    tendencyReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key181')/*主数据区*/,
      fetchMethod: ApproveEfficiencyService.getTendencyReport,
      showLabel: tendencyShowLabel,
      activeConfig: {
        key: 'filterYearMonths',
        array: true
      },
      render: ({ config, context, reportType }) => {
        let { isFetchingData } = context.state;
        let { isLoading, options, dataLength, title } = config;

        const utils = commonUtilsFactory({ context, reportType, config, reportKeyPrefix });
        options = toggleShowLabel({ config, options });
        return (
          <Charts
            allowActivated
            title={title}
            cols={24}
            utils={utils}
            dataLength={dataLength}
            options={options}
            reportKey='tendencyReport'
            reportType='tendency'
            isFetchingData={isFetchingData}
            loading={isLoading}
            compareKey='monthName'
            onActivatedItemChange={context.onChartClick}
            onRef={context.onMountCharts}
          />
        )
      }
    },
    nodeTimeReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key177')/*节点平均时长*/,
      fetchMethod: ApproveEfficiencyService.getNodeTime,
      showLabel: nodeTimeShowLabel,
      activeConfig: {
        key: 'nodeName',
        array: false
      },
      render: ({ config, context, reportType }) => {
        let { isFetchingData } = context.state;
        let { isLoading, options, dataLength, title } = config;

        const utils = commonUtilsFactory({ context, reportType, config, reportKeyPrefix });
        options = toggleShowLabel({ config, options });
        return (
          <VScrollEchartsV2
            allowActivated
            title={title}
            dataLength={dataLength}
            options={options}
            cols={8}
            utils={utils}
            reportKey='nodeTimeReport'
            isFetchingData={isFetchingData}
            loading={isLoading}
            onActivatedItemChange={context.onChartClick}
            onRef={context.onMountCharts}
          />
        )
      }
    },
    formAvgTimeReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key178')/*表单平均时长*/,
      fetchMethod: ApproveEfficiencyService.getFormAvgTime,
      showLabel: formAvgTimeShowLabel,
      activeConfig: {
        key: 'formName1',
        array: false
      },
      render: ({ config, context, reportType }) => {
        let { isFetchingData } = context.state;
        let { isLoading, options, dataLength, title } = config;

        const utils = commonUtilsFactory({ context, reportType, config, reportKeyPrefix });
        options = toggleShowLabel({ config, options });
        return (
          <VScrollEchartsV2
            allowActivated
            title={title}
            dataLength={dataLength}
            options={options}
            cols={8}
            utils={utils}
            reportKey='formAvgTimeReport'
            isFetchingData={isFetchingData}
            loading={isLoading}
            onActivatedItemChange={context.onChartClick}
            onRef={context.onMountCharts}
          />
        )
      }
    },
    formAvgNodeReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key179')/*表单平均节点数*/,
      fetchMethod: ApproveEfficiencyService.getFormAvgNode,
      showLabel: formAvgNodeShowLabel,
      activeConfig: {
        key: 'formName2',
        array: false
      },
      render: ({ config, context, reportType }) => {
        let { isFetchingData } = context.state;
        let { isLoading, options, dataLength, title } = config;

        const utils = commonUtilsFactory({ context, reportType, config, reportKeyPrefix });
        options = toggleShowLabel({ config, options });
        return (
          <VScrollEchartsV2
            allowActivated
            title={title}
            dataLength={dataLength}
            options={options}
            cols={8}
            utils={utils}
            reportKey='formAvgNodeReport'
            isFetchingData={isFetchingData}
            loading={isLoading}
            onActivatedItemChange={context.onChartClick}
            onRef={context.onMountCharts}
          />
        )
      }
    },
    detailListReport: {
      ...COMMON_REPORT_CONFIG,
      title: messages('finance-7.key182')/*明细数据*/,
      fetchMethod: ApproveEfficiencyService.getDetailList,
      isTable: true,
      render: ({ config, context }) => {

        let columnsFetch = () => new Promise(async (resolve, reject) => {
          try {
            let res = await ApproveEfficiencyService.getDetailListColunms();
            let data = res.data;
            //reportColumnDTOList 是报表的列
            //reportColumnCustomizedDTOList是自定义的列，有就显示自定义的
            let column = data.reportColumnDTOList;//默认报表列
            let customColumn = data.reportColumnCustomizedDTOList;//自定义报表列
            let reportColumn = customColumn.length > 0 ? customColumn : column;
            let finalColumns = getReportTableColumn(reportColumn) || [];

            resolve(finalColumns)
          } catch (e) {
            resolve([])
          }
        });

        const reportCode = 'APVAR';
        const exportType = 'REPORT';
        const exportUrl = '/report/api/common/download/by/appr/detail/command';
        let ref = config.ref || {
          state: {}
        };
        let { list = [] } = ref.state;
        let exportDisable = !list.length;
        const { reportId } = context.state;
        let transferredParams = GraphicReportService.getCurrentTransferredParams({ context });
        let exportParams = {
          reportId,
          ...transferredParams
        };
        const utils = commonUtilsFactory({
          allowSetting: false,
          allowExport: true,
          reportCode,
          exportDisable,
          exportParams,
          exportType,
          exportUrl
        });

        return (
          <ReportTable
            title={config.title}
            cols={24}
            utils={utils}
            fetchMethod={config.fetchMethod}
            onRef={context.onMountCharts}
            dataLength={1}
            columnsFetch={columnsFetch}
            reportKey='detailListReport'
          />
        )
      }
    },
  }
}
